package com.warmlight.voicepacket.http;

import android.text.TextUtils;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.Response;

/**
 * 网络库依赖的一些静态方法
 */
public class HttpUtils {

    public static boolean isCodeSuccess(String code){
        if (TextUtils.equals("200",code)){
            return true;
        }
        return false;
    }

    /**
     * 将String解析成bean对象，只适合 data中只有一个对象的情况，如果data中直接是map或者list，会报错
     *
     * @param responseJson
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T json2Bean(String responseJson, Class<T> clazz) throws Exception {
        JSONObject json = null;
        try {
            json = new JSONObject(responseJson);
            int c = json.getInt("code");
            String msg = json.optString("msg");
            if (msg == null) {
                msg = json.optString("message");
            }
            String string = json.optString("data");
            if (clazz != null && !clazz.equals(String.class)) {
                Gson localGson = new Gson();
                try {
                    T data = localGson.fromJson(string, clazz);
                    return data;
                } catch (JsonSyntaxException e) {
                    throw new Exception(new JsonSyntaxException(e));
                }
            } else {
                return (T) string;
            }
        } catch (JSONException e) {
            throw new Exception(e);
        }
    }

    /**
     * 将请求得到的response保存为文件
     *
     * @param response     OKHttp的response
     * @param destFileDir  保存的文件路径
     * @param destFileName 保存的文件名
     * @return
     * @throws IOException
     */
    public static File saveFile(Response response, String destFileDir, String destFileName) throws Exception {
        InputStream is = null;
        byte[] buf = new byte[2048];
        int len = 0;
        FileOutputStream fos = null;
        try {
            is = response.body().byteStream();
            final long total = response.body().contentLength();

            long sum = 0;

            File dir = new File(destFileDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            File file = new File(dir, destFileName);
            try {
                fos = new FileOutputStream(file);
            } catch (FileNotFoundException e) {
                throw new Exception(e);

            }
            try {
                while ((len = is.read(buf)) != -1) {
                    sum += len;
                    fos.write(buf, 0, len);
                }
            } catch (IOException e) {
                throw new Exception(e);
            }
            try {
                fos.flush();
            } catch (IOException e) {
                throw new Exception(e);
            }

            return file;

        } finally {
            try {
                response.body().close();
                if (is != null) is.close();
            } catch (IOException e) {
                throw new Exception(e);
            }
            try {
                if (fos != null) fos.close();
            } catch (IOException e) {
                throw new Exception(e);
            }

        }
    }

}
